package com.zwz.crawler.riskInfo;

import com.zwz.constant.Constant;
import com.zwz.parse.JsonParserUtil;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Slf4j
public class TungeeCourtAnnouncement {
    public static void startTungeeCourtAnnouncement(String  enterpriseId) throws UnsupportedEncodingException {
        // 构建请求参数
//        String enterpriseId = "577de19eadf21dc4";
        int start = 0;
        int end = 5;
        int caTypeOption = 2;
        int status = 0;

        // URL编码处理
        String encodedId = URLEncoder.encode(enterpriseId, "utf-8");

        // 构造完整URL
        String url = "https://sales.tungee.com/api/enterprise/court-announcement/list"
                + "?enterprise_id=" + encodedId
                + "&start=" + start
                + "&end=" + end
                + "&ca_type_option=" + caTypeOption
                + "&status=" + status;

        try {
            Connection.Response response = Jsoup.connect(url)
                    .method(Connection.Method.GET)
                    // 设置完整请求头
                    .header("authority", "sales.tungee.com")
                    .header("accept", "*/*")
                    .header("accept-encoding", "gzip, deflate, br, zstd")
                    .header("accept-language", "zh-CN,zh;q=0.9")
                    .header("cache-control", "no-cache")
                    .header("pragma", "no-cache")
                    .header("priority", "u=1, i")
                    .header("referer", "https://sales.tungee.com/enterprise-details/577de19eadf21dc4/enterprise-information/business-risk")
                    .header("sec-ch-ua", "\"Not;A=Brand\";v=\"24\", \"Chromium\";v=\"128\"")
                    .header("sec-ch-ua-mobile", "?0")
                    .header("sec-ch-ua-platform", "\"Windows\"")
                    .header("sec-fetch-dest", "empty")
                    .header("sec-fetch-mode", "cors")
                    .header("sec-fetch-site", "same-origin")
                    .header("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36")
                    .header("x-tonxis-pid", "67864ea75f69e05d3b544ca7")
//                    .header("cookie", "_tx_pid=67864ea75f69e05d3b544ca7; __wpkreporterwid_=cc4a07fc-7bb9-40a4-96bc-2cbac34b658f; __last_enter_version=sales; _co_i=6805a5576eceb9637696f09d; _tx_uid=680701dddca941522b77e864; _tx_cid=6805a5576eceb9637696f09d; DISTINCT_ID=b84fe276-099f-4932-92b3-d54b92ae384b; _tx_sid=MTc0NTMwMTE0MzYyMjo4MmQ2OTQ5MTY0NjU2ODNmYjQ5MjlmMjc3NDg5ZDFlZg==; Hm_lvt_f2ee75449fc055cc4dbceb4fe403bea3=1745301094,1745302709; HMACCOUNT=B4E402DF057C895E; SecurityCenterDuId=ImFBSG15RzdPdVdPdCtsWnNGMFVuSXhVPSI.GujnjA.YBo4Zvc8vs4jgEmtioacknOQ9pE; tg_referrer_source=https%3A%2F%2Fuser.tungee.com%2F; Hm_lpvt_f2ee75449fc055cc4dbceb4fe403bea3=1745311256; acw_tc=1a0c384f17453698184017570e00605a98e1a4c90bfaaa7d86f0d745f0d5de; accountCenterSessionId=.eJwlzUFLxDAQhuH_kvMeZjLTJLs3tYsXt72sCL2USTKhllKh7aoo_neLHl_4eL5vkwaZZ53MyXxoNAdzW3XpX_PeLoCvHCSnSePRUVRGtNbuo1k196u8a7-99TmaU5Fp1YPpy6LrYE7bcttr_WPaehiar4Rd_by1dTd0DwDttRmfXs6fzeNla8a76nLtpqY-UzfeDzv__09CoQTECErZUS5YgkPFrFFj8eiVJCQbM7CwMqeUvBcCsCAJjgDgS6AcAoswko8kRark2aYKSGLmCjJGBxzAOsbMasEWpV3OntT8_AIOQFR_.GunM6Q.8QBdr-Xkfzi0uQiWY91xsUwqsys; doncusSessionId=eyJfZnJlc2giOmZhbHNlLCJ1c2VyX2lkIjoiNjgwNzAxZGRkY2E5NDE1MjJiNzdlODY0In0.GunM-w.CGkfmJdQV2Xi1xrpII364hvBbDg")
                    .header("cookie", Constant.cookies)
                    .ignoreContentType(true)
                    .ignoreHttpErrors(true)
                    .maxBodySize(0)
                    .timeout(30000)
                    .execute();

            // 结果处理
           log.info("HTTP状态码: " + response.statusCode());
           //log.info("响应内容:\n" + response.body());
            handleErrorCases(response, enterpriseId,caTypeOption,status);

            //解析json
            JsonParserUtil.ParseCourt(response.body());

        } catch (IOException e) {
            System.err.println("网络请求异常: " + e.getMessage());
            e.printStackTrace();
        }
    }

    private static void handleErrorCases(Connection.Response response, String enterpriseId,int caTypeOption,int status) {
        switch (response.statusCode()) {
            case 400:
                System.err.println("[参数错误] 请检查以下内容：");
                System.err.println("1. ca_type_option 参数是否合法（当前值：" + caTypeOption + "）");
                System.err.println("2. status 参数取值范围验证（当前值：" + status + "）");
                break;
            case 401:
                System.err.println("[认证失效] 解决方案：");
                System.err.println("1. 使用浏览器登录后复制最新 Cookie");
                System.err.println("2. 检查是否需要动态生成 x-tonxis-signature 参数");
                System.err.println("3. 企业ID有效性验证：" + enterpriseId);
                break;
            case 403:
                System.err.println("[权限不足] 请确认：");
                System.err.println("1. 当前账户是否有查看法院公告的权限");
                System.err.println("2. 企业ID是否属于当前账户");
                break;
            case 429:
                System.err.println("[请求频繁] 建议添加延时（2-5秒）");
                break;
            default:
                if (response.statusCode() != 200) {
                    System.err.println("未知错误码: " + response.statusCode());
                }
        }
    }

    // 参数验证（在try块开头添加）
    private static void validateParams(int start, int end, int caTypeOption) {
        if (start < 0 || end <= start || (end - start) > 100) {
            throw new IllegalArgumentException("分页参数不合法 start:" + start + " end:" + end);
        }
        if (caTypeOption < 1 || caTypeOption > 3) {
            throw new IllegalArgumentException("ca_type_option 参数取值范围为1-3");
        }
    }
}